from pathlib import Path

import cv2
import torch
import torch.backends.cudnn as cudnn
from numpy import random

import cjc.yolo_path
from cjc import project_setting
from cjc.detector import opt_tool
from cjc.detector.single_image_loader import LoadSingleImage
from cjc.tools.attemp_load import attempt_load
from cjc.tools.logger import Logger
from yolo.utils.datasets import LoadStreams, LoadImages
from yolo.utils.general import increment_path, set_logging, check_img_size, check_imshow, non_max_suppression, \
    apply_classifier, scale_coords, xyxy2xywh, strip_optimizer
from yolo.utils.plots import plot_one_box
from yolo.utils.torch_utils import select_device, TracedModel, load_classifier, time_synchronized


class DetectorSingle:

    def __init__(self, _opt):
        self.save_img = False
        self.opt = _opt
        self.imgsz = self.opt.img_size
        self.save_txt = _opt.save_txt
        self.view_img = _opt.view_img
        self.names = None
        self.single_image_loader = LoadSingleImage()
        self._prepare_detect()
        self.warmed = False
        self.name=_opt.name
        self.log= Logger(self.name)

    def get_name_from_result(self, r: list):
        if r is None or len(r)==0:
            return None
        lines = [_l.split(' ')[0] for _l in r]
        cls = int(lines[0])
        return self.names[cls]

    @staticmethod
    def get_cls_from_result(r: list):
        if r is None or len(r)==0:
            return None
        lines = [_l.split(' ')[0] for _l in r]
        cls = int(lines[0])
        return cls

    def _prepare_detect(self):
        source, weights, view_img, save_txt, imgsz, trace = self.opt.source, self.opt.weights, self.opt.view_img, self.opt.save_txt, self.opt.img_size, not self.opt.no_trace
        self.save_img = not self.opt.nosave and not source.endswith('.txt')  # save inference images
        self.webcam = source.isnumeric() or source.endswith('.txt') or source.lower().startswith(
            ('rtsp://', 'rtmp://', 'http://', 'https://'))

        # Directories
        self.save_dir = Path(
            increment_path(Path(self.opt.project) / self.opt.name, exist_ok=self.opt.exist_ok))  # increment run
        (self.save_dir / 'labels' if save_txt else self.save_dir).mkdir(parents=True, exist_ok=True)  # make dir
        # Initialize
        set_logging()
        self.device = select_device(self.opt.device)
        self.half = self.device.type != 'cpu'  # half precision only supported on CUDA
        # Load model
        # absweight = f'{project_setting.root}/{weights}'
        self.model = attempt_load(weights, map_location=self.device)  # load FP32 model
        stride = int(self.model.stride.max())  # model stride
        self.imgsz = check_img_size(imgsz, s=stride)  # check img_size

        if trace:
            self.model = TracedModel(self.model, self.device, self.opt.img_size)
        if self.half:
            self.model.half()  # to FP16

        if self.opt.source != '-1':
            self.vid_path, self.vid_writer = None, None
            if self.webcam:
                self.view_img = check_imshow()
                cudnn.benchmark = True  # set True to speed up constant image size inference
                self.dataset = LoadStreams(source, img_size=imgsz, stride=stride)
            else:
                self.dataset = LoadImages(source, img_size=imgsz, stride=stride)

        # Get names and colors
        self.names = self.model.module.names if hasattr(self.model, 'module') else self.model.names
        self.colors = [[random.randint(0, 255) for _ in range(3)] for _ in self.names]

        if self.device.type != 'cpu':
            self.model(torch.zeros(1, 3, self.imgsz, self.imgsz).to(self.device).type_as(
                next(self.model.parameters())))  # run once

    def _inference(self, cv_im, identity):

        old_img_w = old_img_h = self.imgsz
        old_img_b = 1
        path, img, im0s, vid_cap, s = self.single_image_loader.get(cv_im)
        img = torch.from_numpy(img).to(self.device)
        img = img.half() if self.half else img.float()  # uint8 to fp16/32
        img /= 255.0  # 0 - 255 to 0.0 - 1.0
        if img.ndimension() == 3:
            img = img.unsqueeze(0)
        # Warmup
        if not self.warmed:
            if self.device.type != 'cpu' and (
                    old_img_b != img.shape[0] or old_img_h != img.shape[2] or old_img_w != img.shape[3]):
                old_img_b = img.shape[0]
                old_img_h = img.shape[2]
                old_img_w = img.shape[3]
                for i in range(3):
                    self.model(img, augment=self.opt.augment)[0]
            self.warmed = True
        # Inference
        pred = self.model(img, augment=self.opt.augment)[0]
        # Apply NMS
        pred = non_max_suppression(pred, self.opt.conf_thres, self.opt.iou_thres, classes=self.opt.classes,
                                   agnostic=self.opt.agnostic_nms)
        return self._process_detection(path, img, im0s, vid_cap, pred, identity)

    def _process_detection(self, path, img, im0s, vid_cap, pred, identity):
        lines = []  # 要保存的结果
        for i, det in enumerate(pred):  # detections per image
            im0 = im0s
            gn = torch.tensor(im0.shape)[[1, 0, 1, 0]]  # normalization gain whwh
            if len(det):
                # Rescale boxes from img_size to im0 size
                det[:, :4] = scale_coords(img.shape[2:], det[:, :4], im0.shape).round()
                for *xyxy, conf, cls in reversed(det):
                    # print(xyxy, conf, cls)
                    xywh = (xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()  # normalized xywh
                    line = (cls, *xywh, conf) if self.opt.save_conf else (cls, *xywh)  # label format
                    lines.append(('%g ' * len(line)).rstrip() % line)
                    if self.save_img or self.view_img:  # Add bbox to image
                        label = f'{self.names[int(cls)]} {conf:.2f}'
                        plot_one_box(xyxy, im0, label=label, color=self.colors[int(cls)], line_thickness=1)
            # Stream results
            if self.view_img:
                cv2.namedWindow(self.name, cv2.WINDOW_NORMAL)
                cv2.imshow(self.name, im0)
                cv2.waitKey(1)  # 1 millisecond
        return lines

    def detect(self, cv_im, identity):
        return self._inference(cv_im, identity)


if __name__ == '__main__':
    opt = opt_tool.create_opt()
    opt.source = '-1'
    opt.view_img = True
    detector = DetectorSingle(opt)

    cp = cv2.imread('/home/cjc/Pictures/heisi.jpg')
    # with torch.no_grad():
    result = detector.detect(cp)
    cv2.waitKey(1000)
